from flask import Flask,render_template,jsonify,request,abort,send_from_directory, redirect, url_for
from gevent import monkey
from gevent.pywsgi import WSGIServer
monkey.patch_all()
import traceback
from requests.api import get
from sqlalchemy import func, and_
from sqlalchemy.log import echo_property
from sqlalchemy.orm import mapper
from sqlalchemy.sql.operators import exists
import  models
from urllib.parse import quote,unquote
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
from werkzeug.utils import secure_filename
import os
import config
from config import debug, init_settings, log as log
from config import makeNewSession as makeNewSession
import re
import time
from uuid import uuid4
from botclass.message import Sender
from botclass.timer import Timer
from API.messageAPI import sendMaster,get_group_info,get_group_list,set_group_leave
from datetime import datetime,timedelta
from routes import login_and_settings, studentsData,groupsData,classes,files,form,formDatabase,botLogic, timer, functions
# 初始化数据库设置
def readSettings():
    session = makeNewSession()
    settings_all = session.query(models.Setting).all()
    session.close()
    adict = {}
    for setting in settings_all:
        if setting.type == "str":
            adict[setting.keyname] = setting.value
        elif setting.type == "int":
            adict[setting.keyname] = int(setting.value)
        elif setting.type == "float":
            adict[setting.keyname] = float(setting.value)
        elif setting.type == "Iterable":
            adict[setting.keyname] = json.loads(setting.value)
        else:
            adict[setting.keyname] = setting.value

    return adict
settings = readSettings()
init_settings(settings)
del settings



app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)  # 设置session

# 学生数据表
app.register_blueprint(studentsData.students,url_prefix='/')
# 群组数据表
app.register_blueprint(groupsData.groups,url_prefix='/')
# 班级数据表
app.register_blueprint(classes.classes,url_prefix='/')
# 文件系统
app.register_blueprint(files.files,url_prefix='/')
# 表单数据
app.register_blueprint(form.form,url_prefix='/form')
# 表单数据库
app.register_blueprint(formDatabase.formDatabase,url_prefix='/formData')
# timer
app.register_blueprint(timer.timer,url_prefix='/')
# 机器人控制逻辑
app.register_blueprint(botLogic.botLogic,url_prefix='/')
# 配置登录页面
app.register_blueprint(login_and_settings.login,url_prefix='/')
# 其它功能模块
app.register_blueprint(functions.functions,url_prefix='/')


@app.before_request
def before_request():
    if not request.path.startswith("/static") and not request.path.startswith("/formData") and not request.path.startswith(url_for('login.loginPage')) and not request.path.startswith("/qqbot"):
        token = request.cookies.get('token')
        # print("get token ", token)
        if not token or not config.certify_token(config.TOKEN_KEY, unquote(token)):
            print("redirect", request.path)
            return redirect(url_for('login.loginPage'),code=302)

@app.route("/index")
def index():
    return render_template("index.html")

@app.route("/")
def homePage():
    return redirect(url_for("index"))



if __name__=="__main__":
    timer_ = Timer()
    timer_.timer_start()
    # app.run(config.HOST,port=config.PORT,debug=False)
    print(f"本地运行请使用浏览器打开 http://127.0.0.1:{config.PORT}")
    app.config.update(DEBUG=False)
    http_server = WSGIServer((config.HOST, config.PORT), app)
    http_server.serve_forever()
